package com.csf.quartz;

import com.csf.config.likeKeyConfig;
import com.csf.entity.DiscussPost;
import com.csf.service.DiscussPostService;
import com.csf.service.ElasticSearchService;
import com.csf.service.likeService;
import com.csf.util.CommunityActivation;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 帖子刷新定时任务，热度排行
 */

public class PostRefreshJob implements Job, CommunityActivation {

    private static final Logger logger = LoggerFactory.getLogger(PostRefreshJob.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private likeService lkservice;

    @Autowired
    private ElasticSearchService elasticSearchService;

//    牛犊子纪元
    private static final Date epcho;

    static {
        try {
            epcho = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-07-01 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException("牛犊子纪元初始化失败",e);
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        直接获取redis中的帖子ID
        String postKey = likeKeyConfig.getPostKey();
        BoundSetOperations ops = redisTemplate.boundSetOps(postKey);
//        首先判断是否有帖子id
        if (ops.size()==0){
            logger.info("[定时任务] 当前没有任务可以更新!");
            return;
        }
//      如果有更新，则可以获取响应的id
//        顺便记录日志
        logger.info("[定时任务] 刷新帖子分数");
        while (ops.size()>0){
            int postId = (Integer) ops.pop();
            this.refreshScore(postId);

        }
        logger.info("[定时任务] 刷新完毕");
    }
//    查看更新的帖子数据之后，然后通过牛犊子算法来计算帖子的权重
    private void refreshScore(int postId){
        DiscussPost discussPost = discussPostService.selectDisById(postId);
//        首先判断帖子是否为空
        if (discussPost == null){
            logger.error("帖子不存在"+postId);
            return;
        }
//        判断当前帖子是否加精
        Boolean addStar = discussPost.getStatus()==1;

//       获取帖子的评论数量
        int commentCount = discussPost.getCommentCount();

//        获取帖子的点赞数量
        int likeCount = lkservice.likeCount(ENTITY_TYPE_POST, postId);

//       算出权重
        double w = (addStar?75:0)+commentCount*10+likeCount*2;
//        算出分数
        double score = Math.log10(Math.max(w,1))+(discussPost.getCreateTime().getTime()-epcho.getTime())/(1000*3600*24);

//        更新帖子分数
        discussPost.setScore(score);
        discussPostService.updateDiscussScore(postId,score);

//        更新es中的状态
        elasticSearchService.saveDiscussPostEs(discussPost);
    }
}
